package com.pan.kang.common.jwt;


import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JwtUtil {

    /**
     * 用来加密数字签名的密钥
     */
    private static final String SECRET_KEY = "SECRET_KEY";

    private static final String ISSUER = "ISSUER";

    public static String createToken(JwtUser jwtUser) {
        JWTCreator.Builder builder = JWT.create();
        return builder.withIssuer(ISSUER)
                .withIssuedAt(jwtUser.getIssuedAt())
                .withKeyId(jwtUser.getUserId())
                .withClaim(JwtConstants.JWT_KEY, JSONUtil.toJsonStr(jwtUser))
                .withExpiresAt(DateUtil.offsetMinute(jwtUser.getIssuedAt(),
                        Integer.parseInt(jwtUser.getExpiresMin() + "")))
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }

    public static JwtUser getJwtUser(String token) {
        DecodedJWT jwt = decodeToken(token);
        if (jwt == null) {
            return null;
        }
        return JSONUtil.toBean(jwt.getClaim(JwtConstants.JWT_KEY).asString(), JwtUser.class);
    }

    public static DecodedJWT decodeToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).withIssuer(ISSUER).build();
            return verifier.verify(token);
        } catch (Exception exception) {
            return null;
        }
    }
}
